package gaml.text.parser;

import gaml.error.GamlException;
import gaml.text.TextNodeBridge;
import gaml.text.YamlParserStore;
import gaml.text.YamlText;
import gaml.text.YamlTextParser;
import gaml.yaml.SequenceNode;
import gaml.yaml.YamlNode;
import gaml.yaml.ahchor.YamlAnchorCodeStore;

import java.util.regex.Pattern;

/**
 * parse sequence node from it's text representation
 * @author shnireck
 *
 */
public class SequenceNodeParser implements YamlTextParser {
	static final String incorrectSequenceNodeFormat = "Mailformed sequence node line [%s] (line number %d)";
	static final Pattern pattern = Pattern.compile ("^- ?(.*)?");
	
	YamlParserStore store = null;
	YamlAnchorCodeStore anchors = null;
	
	public SequenceNodeParser (YamlAnchorCodeStore anchors, YamlParserStore store) {
		this.store = store;
		this.anchors = anchors;
	}
	
	@Override
	public boolean isParserFor (YamlText text) throws GamlException { return "[".equals (text.getValue ()); }
	
	@Override
	public String getParsingTail (YamlText text) throws GamlException { return text.getValue ().substring (1).trim (); }

	@Override
	public YamlNode parseText (YamlText text, YamlNode parent) throws GamlException {
		SequenceNode node = (SequenceNode) new SequenceNode (parent).setTag (text.getTag ());
		node.setAnchor (anchors.getAnchor (text.getAnchor (), node));
		text.next ();
		
		while (! text.isEnd ()) {
			if ("]".equals (text.getValue ())) { text.next (); break; }
			else if (text.getIdentation () < (node.getLevel () + 1)) break;
			else if (isSequensElement (text)) node.addChild (new TextNodeBridge (text.setTail (getParsingTail (text)), node).parseText (store).getNode ());
			else throw new GamlException (String.format (incorrectSequenceNodeFormat, text.getValue (), text.getCurrent ()));
		}
		
		return node;
	}
	
	protected boolean isSequensElement (YamlText text) throws GamlException {
		while (text.getValue ().isEmpty () && (! text.isEnd ())) text.next ();
		return ((! text.isEnd ()) && text.getValue ().startsWith ("-"));
	}
}
